#coding=utf-8
__author__ = 'Meteor'

import requests,jsonpath,json
from tools.loggingModule import logger
from requests.exceptions import MissingSchema
import seting,os

class Reque(object):


    def __init__(self,data):
        self.data = data
        self.response =None


    def send_request(self):

        data = None
        url = None
        method = None
        params = None
        json = None





        if 'url' not in self.data:
            logger.error('url error')
            raise MissingSchema('URL error')
        else:
            url = self.data.get('url')
            logger.info('get url %s' %url)


        if 'headers' in self.data:
            headers = self.data.get("headers")
            logger.info('get headers %s' %headers)

        if 'data' in self.data:
            data = self.data.get('data')
            logger.info('get data %s' %data)
        if 'params'  in self.data:
            params = self.data.get('params')
            logger.info('get params %s' %params)
        if 'json' in self.data:
            json = self.data.get('json')
        if 'method' not in self.data:
            method = "get"
            logger.info('not fond method,default set  %s' %method)
        else:
            method = self.data.get("method")
            logger.info('get method %s' %method)

        # 判断参数是data、params、json
        if  data != None and params != None:
            self.response = requests.request(method=method,url=url,data=data,params=params)
            logger.info('send request method: %s,url:%s,data:%s,params:%s' %(method,url,data,params))
        elif data != None:
            self.response = requests.request(method=method,url=url,data=data)
            logger.info('send request method: %s,url:%s,data:%s' %(method,url,data))
        elif json != None and params != None:
            self.response = requests.request(method=method,url=url,json=data,params=params)
            logger.info('send request method: %s,url:%s,json:%s,params:%s' %(method,url,json,params))
        elif json != None:
            self.response = requests.request(method=method,url=url,json=data)
            logger.info('send request method: %s,url:%s,json:%s' %(method,url,json))
        elif params != None:

            self.response = requests.request(method=method,url=url,params=params)
            logger.info('send request method: %s,url:%s,params:%s' %(method,url,params))

        if 'exten' in self.data:
            info = self.data.get("exten")
            self.setToken(info)

        return self.response

    def get_response(self):
        return self.response

    def setToken(self,exten):
        for k,v in exten.items():
            print("设置token：",self.response.text,v)
            inf = jsonpath.jsonpath(json.loads(self.response.text),v)[0]
            os.environ[k] = inf



